package com.geek.novel.adapter

import android.app.Activity
import android.text.TextUtils
import android.view.MotionEvent
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.geek.novel.utils.FormatUtil
import com.geek.novel.utils.SPUtil
import com.geek.novel.utils.SPUtil.put

/**基础RecyclerView适配器*/
abstract class BaseRecyclerViewAdapter<T: BaseRecyclerViewHolder, E: Any>(val context: Activity, val list: ArrayList<E>): RecyclerView.Adapter<T>() {

    /**是否倒序 */
    private var isSortDesc = false

    //item点击事件监听器
    var onItemClickListener: OnItemClickListener? = null

    //item点击事件监听器
    interface OnItemClickListener {
        fun onItemClick(position: Int, event: MotionEvent?)
    }

    //item点击事件监听器
    var onItemLongClickListener: OnItemLongClickListener? = null

    //item点击事件监听器
    interface OnItemLongClickListener {
        fun onItemLongClick(position: Int, event: MotionEvent?): Boolean
    }

    override fun onBindViewHolder(holder: T, position: Int) {
        holder.bind()
    }


    /**获取排序字段保存到文件中的key*/
    open fun getSortDescSpKey(): String? = null

    /**初始化排序*/
    open fun initSortDesc(){
        val isSortDesc = getSortDesc()
        setSortDesc(isSortDesc)
    }

    /**是否倒序 */
    open fun getSortDesc(): Boolean {
        val key = this.getSortDescSpKey()
        if(TextUtils.isEmpty(key)){
            return isSortDesc
        }
        val bool = SPUtil[key!!, false, SPUtil.SP_SYSTEM_SETUP]
        return FormatUtil.isNullToBoolean(bool, false)
    }

    /**设置是否倒序 */
    open fun setSortDesc(isSortDesc: Boolean) {
        this.isSortDesc = isSortDesc
        val key = this.getSortDescSpKey()
        if(!TextUtils.isEmpty(key)){
            put(key!!, isSortDesc, SPUtil.SP_SYSTEM_SETUP)
        }
    }

    /**获取索引下标，返回的可能是倒序的结果 */
    open fun getIndex(position: Int): Int {
        var index = position
        if (this.isSortDesc) {
            index = list.size - position - 1
        }
        return index
    }


    override fun getItemCount(): Int {
        return list.size
    }

    /**初始化列表*/
    fun initListView(view: RecyclerView){
        view.layoutManager = LinearLayoutManager(context)
        view.adapter = this

        //绑定点击事件
        this.onItemClickListener = object: OnItemClickListener{
            override fun onItemClick(position: Int, event: MotionEvent?) {
                itemClickEvent(list[position])
            }
        }
    }

    /**列表项的点击事件*/
    open fun itemClickEvent(data: E){}

}